import React, { useState, useEffect } from "react";
import {
  Button,
  Form,
  Input,
  Table,
  Space,
  Modal,
  TreeSelect,
  InputNumber,
  message,
} from "antd";
import type { ColumnsType } from "antd/es/table";
import {
  SearchOutlined,
  ReloadOutlined,
  PlusOutlined,
  DeleteOutlined,
  EditOutlined,
  ExclamationCircleFilled,
} from "@ant-design/icons";
import { $get, $post } from "@/api/RestUtils";
import TimeUtils from "@/utils/TimeUtils";
import TreeUtils from "@/utils/TreeUtils";
import "./index.less";
import { useSelector } from "react-redux";

const App: React.FC = () => {
  const permissionList: string[] = useSelector((state: any) => state.permissions);

  const [searchForm] = Form.useForm();
  const [dataForm] = Form.useForm();

  const [infoModalShow, setInfoModalShow] = useState(false);
  const [infoModalTitle, setInfoModalTitle] = useState("");

  const [departmentList, setDepartmentList] = useState<any[]>();
  const [modalDepartmentList, setModalDepartmentList] = useState<any[]>();

  const availableList = [
    {
      available: 0,
      availableName: "锁定",
    },
    {
      available: 1,
      availableName: "正常",
    },
  ];

  const rootNode = {
    key: 0,
    deptId: 0,
    deptName: "Whale Tech",
    sort: 0,
  };
  
  let field = {
    id: "deptId",
    parentId: "parentId"
  }

  const columns: ColumnsType<DepartmentDataType> = [
    {
      title: "部门名称",
      dataIndex: "deptName",
      key: "deptName",
      width: 150,
      align: "center",
    },
    {
      title: "排序",
      dataIndex: "sort",
      key: "sort",
      width: 100,
      align: "center",
    },
    {
      title: "创建时间",
      dataIndex: "ctime",
      key: "ctime",
      width: 240,
      align: "center",
      render: (ctime: Date) => {
        return TimeUtils.format(ctime);
      },
    },
    {
      title: "操作",
      key: "action",
      fixed: "right",
      align: "center",
      width: 400,
      render: (record: any) => {
        return (
          <Space size="middle">
            <Button
              type="link"
              icon={<EditOutlined />}
              size="small"
              onClick={() => switchDataModalShow(true, 1, record)}
              disabled={
                !permissionList ||
                !permissionList.includes("system.department:update")
              }
            >
              修改
            </Button>
            <Button
              type="link"
              icon={<DeleteOutlined />}
              size="small"
              onClick={() => deleteDepartmentConfirm(record.deptId)}
              disabled={
                !permissionList ||
                !permissionList.includes("system.department:delete")
              }
            >
              删除
            </Button>
          </Space>
        );
      },
    },
  ];

  useEffect(() => {
    search();
  }, []);

  const switchDataModalShow = (show: boolean, model: number, formData: any) => {
    setInfoModalShow(show);
    if (model === 0) {
      // 新增
      setInfoModalTitle("新增部门信息");
    } else {
      // 修改
      setInfoModalTitle("修改部门信息");
      dataForm.setFieldsValue(formData);
    }
  };

  const closeModal = () => {
    setInfoModalShow(false);
    resetDataForm();
  };

  const saveOrUpdate = (formData: any) => {
    let url;
    if (formData.deptId != null) {
      url = "/department/update";
    } else {
      url = "/department/save";
    }
    $post(url, formData)
      .then((res: any) => {
        if (res.code === 0) {
          message.success(res.msg);
          search();
          closeModal();
        } else {
          message.error(res.msg);
        }
      })
      .catch((err: any) => {
        message.error("系统异常");
      });
  };

  const deleteDepartmentConfirm = (deptId: number) => {
    Modal.confirm({
      title: "是否删除当前部门？",
      icon: <ExclamationCircleFilled />,
      okText: "是",
      cancelText: "否",
      onOk() {
        deleteDepartment(deptId);
      },
    });
  };

  const deleteDepartment = (deptId: number) => {
    let param = {
      deptId: deptId,
    };
    $get("/department/delete", param)
      .then((res: any) => {
        if (res.code === 0) {
          message.success(res.msg);
          search();
        } else {
          message.error(res.msg);
        }
      })
      .catch((err: any) => {
        message.error("系统异常");
      });
  };

  const search = () => {
    $get("/department/find", searchForm.getFieldsValue())
      .then((res: any) => {
        if (res.code === 0) {
          let departmentList = TreeUtils.list2Tree(res.data, field);
          setDepartmentList(departmentList);
          res.data.push(rootNode);
          let modalDepartmentList = TreeUtils.list2Tree(res.data, field);
          setModalDepartmentList(modalDepartmentList);
        } else {
          message.error(res.msg);
        }
      })
      .catch((err: any) => {
        message.error("系统异常");
      });
  };

  const resetDataForm = () => {
    dataForm.resetFields();
  };

  const resetSearchForm = () => {
    searchForm.resetFields();
  };

  return (
    <>
      <Modal
        title={infoModalTitle}
        open={infoModalShow}
        closable={true}
        onCancel={closeModal}
        footer={null}
        className="department-save-modal"
      >
        <Form
          form={dataForm}
          labelAlign="right"
          layout="vertical"
          colon={false}
          onFinish={saveOrUpdate}
        >
          <Form.Item name="deptId" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item
            name="deptName"
            label="部门名称"
            rules={[
              { required: true, type: "string", message: "请输入部门名称" },
              { max: 12, min: 2, message: "长度在2~12位之间" },
            ]}
          >
            <Input placeholder="部门名称" maxLength={12} />
          </Form.Item>
          <Form.Item
            name="sort"
            label="排序值"
            rules={[
              { required: true, type: "number", message: "请输入排序值" },
              { max: 99, min: 0, type: "number", message: "数值在0~99位之间" },
            ]}
          >
            <InputNumber placeholder="排序值" maxLength={3} />
          </Form.Item>
          <Form.Item
            name="parentId"
            label="上级部门"
            rules={[{ required: true, message: "请输入选择上级部门" }]}
          >
            <TreeSelect
              showSearch
              style={{ width: "100%" }}
              dropdownStyle={{ maxHeight: 400, overflow: "auto" }}
              placeholder="请选择上级部门"
              allowClear
              treeData={modalDepartmentList}
              fieldNames={{
                label: "deptName",
                value: "deptId",
                children: "children",
              }}
            />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              保存
            </Button>
            <Button onClick={resetDataForm}>重置</Button>
          </Form.Item>
        </Form>
      </Modal>
      <div className="department-body">
        <div className="search-condition">
          <Form
            form={searchForm}
            labelAlign="left"
            name="horizontal_login"
            colon={false}
          >
            <div className="form-body">
              <Form.Item name="deptName" label="部门名称">
                <Input placeholder="部门名称" maxLength={12} />
              </Form.Item>
            </div>
            <div className="form-footer">
              <Form.Item>
                <Button
                  type="primary"
                  icon={<SearchOutlined />}
                  onClick={() => search()}
                >
                  查询
                </Button>
                <Button icon={<ReloadOutlined />} onClick={resetSearchForm}>
                  重置
                </Button>
              </Form.Item>
            </div>
          </Form>
        </div>
        <div className="table-area">
          <div className="operate-btn-group">
            <Button
              type="dashed"
              icon={<PlusOutlined />}
              onClick={() => switchDataModalShow(true, 0, null)}
              disabled={
                !permissionList ||
                !permissionList.includes("system.department:save")
              }
            >
              新增
            </Button>
          </div>
          <div className="table-data">
            <Table
              pagination={false}
              dataSource={departmentList}
              columns={columns}
              scroll={{ x: 1200 }}
            />
          </div>
        </div>
      </div>
    </>
  );
};

export default App;
